package com.shipwe.loans.utils.helper

import com.shipwe.loans.MyApps
import com.shipwe.loans.http.ApiService
import com.shipwe.loans.http.ApiService.addCommonParams
import com.shipwe.loans.http.HttpHelper
import com.shipwe.loans.http.IHttpCallback
import com.shipwe.loans.utils.ShipweDateUtil
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/20 18:06
 * @Annotation：保存自定义数据接口 参数
 */
object CustomDataHelper {

    /**
     * userName                         : 用户名
     * userBirthday                     ： 用户生日（时间戳 秒）
     * userAvatarUrl                    ： 用户头像链接
     * birthdayPointsReceiveTime        ： 生日福利领取时间（时间戳 秒）
     * isSignReminder                   ： 是否开启签到提醒（Boolean）
     * signReminderPointsReceiveTime    ： 签到提醒积分领取时间（时间戳 秒）
     * repaymentPointsReceiveTime       ： 首次还款积分领取时间（时间戳 秒 暂定）
     * luckyDrawCount                   ： 幸运抽奖次数
     * luckyDrawLastTime                ： 上一次幸运抽奖时间（时间戳 秒）
     * signDurationPointsReceiveTime    ： 本月连续签到15天积分领取时间（时间戳 秒）
     */

    /**
     * 获取保存的自定义数据
     */
    fun getAppCustomData(): JSONObject {
        val customData = ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_CUSTOM_DATA)
        if (customData.isEmpty()){
            return JSONObject()
        }
        return JSONObject(customData)
    }

    /**
     * 获取用户昵称
     */
    fun getShipweCustomUserName(): String{
        val data = getAppCustomData()
        return data.optString("userName","Hello")
    }

    /**
     * 获取用户头像地址
     */
    fun getShipweCustomUserAvatarUrl(): String{
        val data = getAppCustomData()
        return data.optString("userAvatarUrl","")
    }

    /**
     * 获取用户生日(时间戳 秒)
     */
    fun getShipweCustomUserBirthday(): String{
        val data = getAppCustomData()
        return data.optString("userBirthday","")
    }

    /**
     * 保存用户昵称
     */
    fun saveShipweCustomUserNameAction(userName: String){
        val obj = getAppCustomData()
        obj.put("userName",userName)
        saveShipweCustomDataAction(obj)
    }

    /**
     * 保存用户头像id
     */
    fun saveShipweCustomUserAvatar(imgUrl: String){
        val obj = getAppCustomData()
        obj.put("userAvatarUrl",imgUrl)
        saveShipweCustomDataAction(obj)
    }

    /**
     * 获取生日福利领取时间戳（秒）
     */
    fun getShipweCustomBirthdayReceiveTimestamp(): String{
        val data = getAppCustomData()
        return data.optString("birthdayPointsReceiveTime","")
    }

    /**
     * 获取剩余抽奖次数
     */
    fun getShipweCustomLuckyDrawCount(): Int{
        val data = getAppCustomData()
        //上一次抽奖时间戳（秒）
        val luckyDrawLastTime = data.optString("luckyDrawLastTime","")
        //没有抽过奖
        if (luckyDrawLastTime.isEmpty()){
            return 3
        }
        //上次抽奖日期 != 今天
        if (!ShipweDateUtil.IsToday(luckyDrawLastTime.toLong() * 1000)){
            return 3
        }
        return data.optInt("luckyDrawCount",3)
    }

    /**
     * 获取是否开启签到提醒
     */
    fun getShipweCustomIsSignReminder(): Boolean{
        val data = getAppCustomData()
        return data.optBoolean("isSignReminder",false)
    }

    /**
     * 获取签到提醒积分领取时间（时间戳 秒）
     */
    fun getShipweCustomSignReminderPointsReceiveTimestamp(): String{
        val data = getAppCustomData()
        return data.optString("signReminderPointsReceiveTime","")
    }

    /**
     * 本月连续签到15天积分领取时间（时间戳 秒）
     */
    fun getShipweCustomSignDurationPointsReceiveTimestamp(): String{
        val data = getAppCustomData()
        return data.optString("signDurationPointsReceiveTime","")
    }

    /**
     * 保存用户生日(时间戳 秒)
     */
    fun saveShipweCustomUserBirthday(timestamp: String){
        val obj = getAppCustomData()
        obj.put("userBirthday",timestamp)
        saveShipweCustomDataAction(obj)
    }

    /**
     * 保存生日福利领取记录时间戳（秒）
     */
    fun saveShipweCustomUserBirthdayBenefitsReceiveTime(timestamp: String, callback: IHttpCallback){
        val obj = getAppCustomData()
        obj.put("birthdayPointsReceiveTime",timestamp)
        saveShipweCustomDataAction(obj,callback)
    }

    /**
     * 保存用户剩余抽奖次数
     */
    fun saveShipweCustomLuckyDrawCount(count: String){
        val obj = getAppCustomData()
        obj.put("luckyDrawCount",count)
        obj.put("luckyDrawLastTime","${System.currentTimeMillis() / 1000}")
        saveShipweCustomDataAction(obj)
    }

    /**
     * 保存用户是否开启签到提醒
     */
    fun saveShipweCustomSignReminder(){
        val obj = getAppCustomData()
        obj.put("isSignReminder", !getShipweCustomIsSignReminder())
        saveShipweCustomDataAction(obj)
    }

    /**
     * 保存用户领取签到提醒任务积分的时间（时间戳 秒）
     */
    fun saveShipweCustomSignReminderPointsTimestamp(){
        val obj = getAppCustomData()
        obj.put("isSignReminder", true)
        obj.put("signReminderPointsReceiveTime","${System.currentTimeMillis() / 1000}")
        saveShipweCustomDataAction(obj)
    }

    /**
     * 保存用户领取本月连续签到15天任务积分的时间（时间戳 秒）
     */
    fun saveShipweCustomSignDurationPointsReceiveTimestamp(){
        val obj = getAppCustomData()
        obj.put("signDurationPointsReceiveTime","${System.currentTimeMillis() / 1000}")
        saveShipweCustomDataAction(obj)
    }

    /**
     * 获取自定义数据
     */
    fun loadShipweCustomDataAction(){
        val httpUrl = ApiService.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.SHIPWE_API_LOAD_CUSTOM_PARAMS_PATH)
        }
        HttpHelper.post(httpUrl,params,this,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null && obj.has("userInfo")){
                            val userInfo = obj.optString("userInfo")
                            //保存自定义数据
                            ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_CUSTOM_DATA,userInfo.toString())
                            //通知自定义数据刷新完成
                            MyApps.app.publisher.publish(AppEventData(AppEventData.TYPE.SHIPWE_CUSTOM_DATA_REFRESHED))
                        }
                    }
                    else -> {
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 保存数据
     */
    private fun saveShipweCustomDataAction(obj: JSONObject, callback: IHttpCallback? = null){
        val httpUrl = ApiService.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.SHIPWE_API_SAVE_CUSTOM_PARAMS_PATH)
            put("userInfo",obj.toString())
        }
        HttpHelper.post(httpUrl,params,this,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                callback?.onRequestSuccess(data)
                when(data.optInt("code")) {
                    0 -> {//成功
                        val jsonObj = data.optJSONObject("obj")
                        if (jsonObj != null){
                            //保存成功 再更新数据
                            loadShipweCustomDataAction()
                        }
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                callback?.onRequestError(error)
            }

            override fun onRequestFinish() {
                callback?.onRequestFinish()
            }
        })
    }
}